#include <stdlib.h>
#include <time.h>
#include <process.h>
#include "SkypeCommand.h"

//
unsigned long SkypeCommand::_cmdCounter = (unsigned long)time(0);
//
SkypeCommand::SkypeCommand(const TCHAR* cmd) {
	_cmdNo = _cmdCounter++;
	size_t len = _tcslen(cmd);
	_cmd = (TCHAR*)malloc(len * sizeof(TCHAR));
    int n;
	while ((n = _sntprintf_s(_cmd, len, len - 1, TEXT("#%lu %s"), _cmdNo, cmd)) == -1) {
        len <<= 1;
        _cmd = (TCHAR*)realloc(_cmd, len * sizeof(TCHAR));
    };
	_cmd = (TCHAR*)realloc(_cmd, (n + 1) * sizeof(TCHAR));
}
//
bool SkypeCommand::sendTo(SkypeCommWindow& skypeCommWindow) {
   
	skypeCommWindow.sendCommand(_cmd);
	List<tstring>& respList = skypeCommWindow.getRawResponse();
    ULONGLONG t = GetTickCount64();
    bool skypeRespFound = false;
    while(!skypeRespFound && (GetTickCount64() < t + SEND_TO_TIMEOUT) ) {
        if (respList.wait(RESP_TIMEOUT)) {
            respList.lock();
            skypeRespFound = _findSkypeResponse(respList, respList.end(), _response);
            respList.unlock();
        }
    }
    if (skypeRespFound) {
        _beginthread(_thrProcessCommand, 0, (void*) new ProcessArg(*this, skypeCommWindow, _cmdNo, _response));
    }
	return skypeRespFound;
}
//
void SkypeCommand::processCommand(ProcessArg* arg) {
}
//
void __cdecl SkypeCommand::_thrProcessCommand(void* data) {
    ProcessArg* arg = (ProcessArg*) data;
    arg->getSkypeCommand().processCommand(arg);
    delete arg;
}
//
bool SkypeCommand::_findSkypeResponse(const TContainer& container, const TContainer::const_iterator& end, std::vector<tstring>& response) {
    for(TContainer::const_iterator itr = container.begin(); itr != end; ++itr) {
        if (*((*itr).begin()) != TEXT('#'))
            continue;
        //#0 CALL 6093 STATUS UNPLACED
        split(*itr, response);
        long cmdNo = _tstol(response[0].substr(1, response[0].size() - 1).c_str());
        if (cmdNo == _cmdNo) {
            return true;
        }
    }
    return false;
}
//
SkypeCommand::~SkypeCommand() {
	if (_cmd != 0)
		free(_cmd);
}
//
